import { Component, ViewChild, ElementRef } from '@angular/core';
import { PaginationInstance } from 'ngx-pagination';
import { EChartOption, ECharts } from 'echarts-ng2';
import { ActivatedRoute, Params } from '@angular/router';
import * as _ from 'lodash';

import { SignalRService } from 'service/SignalRService';
import { QuoteRealTime } from 'model/QuoteRealTime';
import { ApiRequest } from 'service/ApiRequest';
import { setLocalItem, getLocalItem } from 'utils/index';

import { TradeService } from '../TradeService';

@Component({
  selector: 'market-detail',
  templateUrl: './MarketDetail.html',
  providers: [TradeService]
})
export class MarketDetailComponent {

  private pagination: PaginationInstance = {
    id: 'market-list',
    itemsPerPage: 10,
    currentPage: 0,
    totalItems: 1000
  };
  calculatedHeight: number;//计算后高亮度
  symbol = '';
  category = '';

  realTimeList = [];
  signalRService: SignalRService = new SignalRService('forexHub');

  categoryList = [];
  symbolHistory = [];

  constructor(private route: ActivatedRoute, private apiRequest: ApiRequest, private tradeService: TradeService) {
    tradeService.setParams('http://114.55.146.142:2004', '/api/data/GetApiUrl');
  }

  async ngOnInit() {
    await this.tradeService.init();
    this.route.params.subscribe((params: Params) => {
      this.symbol = params['id'];
      this.loadCategory();

      this.signalRService.registerOn("onNewBasicProductInfoStr", (symbol, data) => {
        const list = data.split("-");

        let floating = 0;
        let percent = 0;

        if (parseFloat(list[4]) !== 0 && parseFloat(list[5]) !== 0 && parseFloat(list[5]) !== 0) {
          floating = parseFloat(list[7]) - parseFloat(list[4]);
          percent = floating / parseFloat(list[4]) * 100;
        }

        const quoteBasic = {
          Symbol: list[0],
          Time: parseInt(list[1]) * 1000,
          Volume: list[2],
          YesterdayClose: parseFloat(list[3]),
          DayOpen: parseFloat(list[4]),
          DayHigh: parseFloat(list[5]),
          DayLow: parseFloat(list[6]),
          CurrentPrice: parseFloat(list[7]),
          BuyPrice: parseFloat(list[8]),
          SellPrice: parseFloat(list[9]),
          floating: floating,
          percent: percent
        };
        const index = _.findIndex(this.symbolHistory, item => item.Symbol === symbol);

        if (index > -1) {
          this.symbolHistory[index]['quote'] = quoteBasic;
        }

        if (symbol === this.symbol) {
          this.realTimeList.unshift(quoteBasic);
          // this.realTimeList = this.realTimeList.slice(0, 16);
          this.realTimeList = this.realTimeList.slice(0, 13);
        }
      });

      this.signalRService.getConnection().done((data: any) => {
        this.signalRService.subscribe(this.symbol);
      }).fail((error: any) => {
        console.log('Could not connect ' + error);
      });
    });
  }

  async loadCategory() {
    // const list = await this.apiRequest.getProductMeta();
    const list = await this.tradeService.getProductMeta();
    this.categoryList = list;
    const index = _.findIndex(list, item => item.Symbol === this.symbol);
    this.category = list[index].CategoryDisplay;

    let symbolList = getLocalItem("symbolHistory");

    if (!symbolList && symbolList.length == 0) {
      this.symbolHistory = [];
      setLocalItem('symbolHistory', [this.symbol]);
    } else {
      this.symbolHistory = list.filter((item) => symbolList.indexOf(item.Symbol) > -1);

      const i = symbolList.indexOf(this.symbol);
      if (i === -1) {
        symbolList.unshift(this.symbol);
        setLocalItem('symbolHistory', symbolList);
      }
    }

    this.signalRService.getConnection().done((data: any) => {
      this.signalRService.subscribe(symbolList.join(";"));
    }).fail((error: any) => {
      console.log('Could not connect ' + error);
    });
  }
}